<?php
/**
 * Created by PhpStorm.
 * User: 雨寒
 * Date: 2018/8/28
 * Time: 下午5:22
 */
namespace app\common\model;

use think\Cache;
use think\Exception;
use think\exception\DbException;
use think\Model;
use think\Db;
class Chat extends Common
{
    /**
     * 对话列表
     *
     */
    static public function talkList($user,$page,$page_size)
    {
        $messagelist=Db::name('message')
            ->where('send_uid',$user['id'])
            ->whereOr('get_uid',$user['id'])
            ->page($page,$page_size)
            ->group('sorts')
            ->order('max(`id`) desc')
            ->select();

        foreach($messagelist as &$item){

            $sorts = $item['send_uid']>$item['get_uid']?$item['get_uid'].'.'.$item['send_uid']:$item['send_uid'].'.'.$item['get_uid'];

            $item=Db::name('message')
                ->where('sorts',$sorts)
                ->order('id desc')
                ->find();

            $item['ctime'] = friend_date($item['ctime']);
            /*--接下来获取和谁聊天--*/
            $item['talk_manid'] = $item['send_uid']==$user['id']?$item['get_uid']:$item['send_uid'];

            //否则，读取该用户头像和昵称
            $uinfo1 = User::exists($item['talk_manid']);
            $item['username']=$uinfo1['real_name'];
            $item['headimg'] =$uinfo1['avatar'];
            $item['bussiness'] = Db::name('bussiness')->where('id',$uinfo1['bussiness_id'])->value('title');
            $item['tip']= self::gestrtype($item['ty'],$item['content'],$item['savename']);

            //获取未读
            $count = Db::name('message')
                ->where('sorts',$item['sorts'])
                ->where('get_uid',$user['id'])
                ->where('status',1)
                ->count();
            $item['noreadernum'] = $count;
        }

        return empty($messagelist)?array():$messagelist;

    }

    /**
     * 对话历史
     *
     */
    static public function history($user,$getid,$page,$page_size)
    {
        $getid = intval($getid);
        /*--判断聊天对象--*/
        if($getid==$user['id']){
            throw new UserException("不能与自己私信！");
        }
        /*--获取对方头像昵称信息--*/
        $chat_maninfo = User::exists($getid);
        if(empty($chat_maninfo)){
            throw new UserException("对方不存在，无法发起私信！");
        }
        if($chat_maninfo['in_blacklist']==1){
            throw new UserException("对方被加入黑名单，无法发起私信！");
        }


        $chat_list=Db::name('message')
            ->where("send_uid=".$getid." and get_uid=".$user['id'])
            ->whereOr("send_uid=".$user['id']." and get_uid=".$getid)
            ->order('id asc')
            ->page($page,$page_size)
            ->select();

        foreach ($chat_list as &$item)
        {
            if ($getid == $item['send_uid']){
                $item['head_img'] = $chat_maninfo['avatar'];
                $item['show_name'] = $chat_maninfo['real_name'];
            }else{
                $item['head_img'] = $user['avatar'];
                $item['show_name'] = $user['real_name'];
            }

            //屏蔽关键词
            if($item['ty']==1)
            {
                $item['content']=self::getcheckmessage($item['content']);
            }
            //若为文件获取字节
            if($item['ty']==3)
            {
                $item['savebyte']=self::getFilesize($item['savebyte']);
            }

            $item['ctime'] = friend_date($item['ctime']);
        }
        $chat_list = empty($chat_list) ? [] : $chat_list;

        return $chat_list;

    }

    /*--消息预览页面显示内容--*/
    static public function gestrtype($ty,$con,$fname){
        if($ty==1){
            return $con;
        }else if($ty==2){
            return '发送了一张图片';
        }else if($ty==3){
            return '发送了文件:'.$fname;
        }else if($ty==4){
            return '发送了一条语音('.$fname.')S';
        }
    }

    /**
     *对话详情
     **/
    static public function message($user,$getid)
    {   $getid = intval($getid);
        /*--判断聊天对象--*/
        if($getid==$user['id']){
            throw new UserException("不能与自己私信！");
        }
        /*--获取对方头像昵称信息--*/
        $chat_maninfo = User::exists($getid);
        if(empty($chat_maninfo)){
            throw new UserException("对方不存在，无法发起私信！");
        }
        if($chat_maninfo['in_blacklist']==1){
            throw new UserException("对方被加入黑名单，无法发起私信！");
        }

        //再读取双方当前聊天信息
        $noread = Db::name('message')
            ->where('get_uid',$user['id'])
            ->where('send_uid',$getid)
            ->where('status',1)
            ->order('id asc')
            ->find();
        if($noread && $noread['ctime']>0){
            //有未读信息 从未读信息开始拉取 24小时私信
            $time_pre = $noread['ctime']-(24*3600);
        }else{
            //无未读信息 获取近24小时
            $time_pre = time()-24*3600;
        }

        //读取记录
        $chat_list= Db::name('message')
            ->where("send_uid=".$getid." and get_uid=".$user['id']." and ctime>'".$time_pre."'")
            ->whereOr("send_uid=".$user['id']." and get_uid=".$getid." and ctime>'".$time_pre."'")
            ->select();

        foreach ($chat_list as &$item)
        {
            //屏蔽关键词
            if($item['ty']==1)
            {
                $item['content']=self::getcheckmessage($item['content']);
            }
            //若为文件获取字节
            if($item['ty']==3)
            {
                $item['savebyte']=self::getFilesize($item['savebyte']);
            }

            $item['ctime'] = friend_date($item['ctime']);

        }

        /*把未读的信息改为已读*/
        Db::name('message')
            ->where('get_uid',$user['id'])
            ->where('send_uid',$getid)
            ->where('status',1)
            ->update(array(
                "status"=>2
            ));

        $chat_list = empty($chat_list) ? [] : $chat_list;

        $list = [
            'uinfo'=>$user,
            'chat_maninfo'=>$chat_maninfo,
            'chat_list'=>$chat_list
        ];
        return $list;
    }

    /**
     *保存对话详情
     **/
    static public function savemessage($user,$get_uid,$content)
    {
        /*--判断聊天对象--*/
        if($get_uid==$user['id']){
            throw new UserException("不能与自己私信！");
        }
        /*--获取对方头像昵称信息--*/
        $get_uid = intval($get_uid);
        $chat_maninfo = User::exists($get_uid);
        if(empty($chat_maninfo)){
            throw new UserException("对方不存在，无法发起私信！");
        }
        if($chat_maninfo['in_blacklist']==1){
            throw new UserException("对方被加入黑名单，无法发起私信！");
        }

        $now_userid = $user['id'];
        $content  = strip_tags($content);
        $content = htmlspecialchars($content);;

        $sorts = $now_userid>$get_uid?$get_uid.'.'.$now_userid:$now_userid.'.'.$get_uid;

        $data=array(
            "send_uid"=>$now_userid,
            "get_uid"=>$get_uid,
            "content"=>$content,
            "ctime"=>time(),
            "status"=>1,
            "sorts"=>$sorts
        );
        $s=Db::name('message')
            ->insertGetId($data);

        if(!$s){
            throw new DeveloperException('服务器繁忙，请稍候再试');
        }

        return 'success';
    }

    /**
     *拉取对话
     **/
    static public function loadmessage($user,$get_uid,$lastid)
    {
        /*--判断聊天对象--*/
        if($get_uid==$user['id']){
            throw new UserException("不能与自己私信！");
        }
        /*--获取对方头像昵称信息--*/
        $get_uid = intval($get_uid);
        $chat_maninfo = User::exists($get_uid);
        if(empty($chat_maninfo)){
            throw new UserException("对方不存在，无法发起私信！");
        }
        if($chat_maninfo['in_blacklist']==1){
            throw new UserException("对方被加入黑名单，无法发起私信！");
        }

        $uinfo= $user;
        $map['get_uid']  = $uinfo['id'];

        $map['send_uid'] = $get_uid;

        $lastid	= intval($lastid);//先去空格再取整，防止非法(非数字)数据传递
        if(empty($lastid)){//未获取$lastid,说明是第一次聊天，id大于0即可
            $map_str = " id>0";
            $map_str.= " and get_uid='".$map['get_uid']."' ";
            $map_str.= " and send_uid='".$map['send_uid']."' ";
        }else{
            $map_str= " id>'".$lastid."' ";
            $map_str.= " and get_uid='".$map['get_uid']."' ";
            $map_str.= " and send_uid='".$map['send_uid']."' ";
        }

        $one_row=Db::name('message')
            ->where($map_str)
            ->find();

        if($one_row){
            @Db::name('message')
                ->where('id',$one_row['id'])
                ->update(['status'=>2]);
            //屏蔽关键词
            if($one_row['ty']==1)
            {
                $one_row['content']=self::getcheckmessage($one_row['content']);
            }
            //若为文件获取字节
            if($one_row['ty']==3)
            {
                $one_row['savebyte']=self::getFilesize($one_row['savebyte']);
            }

            $one_row['ctime'] = friend_date($one_row['ctime']);
        }

        return empty($one_row) ? [] : $one_row;

    }

    /*--屏蔽部分关键词--*/
    static public function getcheckmessage($content){
        $key_str = '约炮 法轮';
        $key_list = explode(' ',$key_str);
        foreach($key_list as $k=>$v){
            $v = trim($v);
            if(!empty($v)){
                $content = str_replace($v, '**', $content);
            }
        }
        return $content;
    }


    /**
     *获取字节
     **/
    static public function getFilesize($num){
        $p = 0;
        $format='bytes';
        if($num>0 && $num<1024){
            $p = 0;
            return number_format($num).' '.$format;
        }
        if($num>=1024 && $num<pow(1024, 2)){
            $p = 1;
            $format = 'KB';
        }
        if ($num>=pow(1024, 2) && $num<pow(1024, 3)) {
            $p = 2;
            $format = 'MB';
        }
        if ($num>=pow(1024, 3) && $num<pow(1024, 4)) {
            $p = 3;
            $format = 'GB';
        }
        if ($num>=pow(1024, 4) && $num<pow(1024, 5)) {
            $p = 3;
            $format = 'TB';
        }
        $num /= pow(1024, $p);
        return number_format($num, 3).' '.$format;
    }


}

